package demo01;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class Accont{
    private String name;
    private int asset;
    private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    public Accont(String name,int asset){
        this.name = name;
        this.asset = asset;
    }
    public void save(int asset){
        this.readWriteLock.writeLock().lock();
        try {
            this.asset += asset;
            TimeUnit.SECONDS.sleep(1);
            System.out.println("【" + Thread.currentThread().getName()+"】修改银行资产，当前的资产为："+(this.asset/100.0));
        }catch (Exception e){}
        finally {
            this.readWriteLock.writeLock().unlock();
        }
    }
    public String toString(){
        this.readWriteLock.readLock().lock();
        try {
            TimeUnit.MICROSECONDS.sleep(1);
            return "【" + Thread.currentThread().getName()+"】账户名称："+this.name+"、账户余额："+(this.asset/100.0);
        }catch (Exception e){
            return null;
        }
        finally {
            this.readWriteLock.readLock().unlock();
        }
    }
}
public class Reendemo02 {
    public static void main(String[] args)throws  Exception {
        Accont accont = new Accont("张三",0);
        int money[] = new int[]{110,230,10_100};
        for (int x = 0;x<10;x++){
            if (x % 2 == 0){
                new Thread(( ) -> {
                    for (int y = 0;y<money.length;y++){
                        accont.save(money[y]);
                    }
                },"存款者 - " + x).start();
            }
            else {
                new Thread(( ) -> {
                    while (true){
                        System.out.println(accont);
                    }
                },"查询者 - " + x).start();
            }
        }
    }
}